package cn.itcast.bos.web.action;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Controller
@Namespace("/")
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Action(value = "customer_sendSms")
	public String sendSms() throws Exception {
		System.out.println("hello");
		// 手机号保存在customer对象中
		// 生成短信验证码
		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码保存到session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成的手机验证码为:" + randomCode);

		// 编辑短信内容
		String msg = "尊敬的用户您好,本次获取的验证码为:" + randomCode + ",服务电话:10086";
		// 通过Sms服务器发送短信
		// String result = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);

		// 假设服务器发送成功
		String result = "000/xxx";
		if (result.startsWith("000")) {
			return NONE;
		} else {
			throw new RuntimeException("短信发送失败,信息码:" + result);
		}
	}

	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value = "customer_regist", results = {
			@Result(name = "success", location = "/signup-success.html", type = "redirect"),
			@Result(name = "input", location = "/signup.html", type = "redirect") })
	public String regist() {
		String session = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(model.getTelephone());
		if (session == null || !session.equals(checkcode)) {
			System.out.println("验证码错误,请重新注册...");
			return "input";
		} else {
			System.out.println("注册成功...");
			return SUCCESS;
		}

	}
}
